﻿using System;
using Microsoft.Practices.ServiceLocation;
using Pap.Core.Utilities;
using Pap.Data;
using Pap.Data.Abstraction.Utils;
using Pap.Services;
using Pap.Services.WorkflowEngine;
using Pap.Web.Utils;

namespace Pap.Web.Modules.Loan.ViewModel
{
    /// <summary>
    /// 
    /// </summary>
    public class ClientProsecutionViewModel : IViewModel
    {
        /// <summary>
        /// 
        /// </summary>
        ILoanRepository _LoanRepository;
        /// <summary>
        /// 
        /// </summary>
        IWorkflowService _WfService;
        /// <summary>
        /// Initializes a new instance of the <see cref="ClientProsecutionViewModel"/> class.
        /// </summary>
        /// <param name="loanRepository">The loan repository.</param>
        /// <param name="workflowService">The workflow service.</param>
        public ClientProsecutionViewModel(ILoanRepository loanRepository, IWorkflowService workflowService)
        {
            _LoanRepository = loanRepository;
            _WfService = workflowService;
        }

        /// <summary>
        /// Gets the loan.
        /// </summary>
        /// <param name="loanID">The loan ID.</param>
        /// <returns></returns>
        public ICustomerLoan GetLoan(Guid loanID)
        {
            return _LoanRepository.GetCustomerLoanByID(loanID);
        }

        /// <summary>
        /// Creates the loan case.
        /// </summary>
        /// <param name="loanID">The loan ID.</param>
        /// <param name="caseNumber">The case number.</param>
        /// <param name="notes">The notes.</param>
        /// <param name="caseDate">The case date.</param>
        public void CreateLoanCase(Guid loanID, long caseNumber, string notes, DateTime caseDate)
        {
            using (IUnitOfWork trans = ServiceLocator.Current.GetInstance<IUnitOfWork>())
            {
                ILoanCase loanCase = ServiceLocator.Current.GetInstance<ILoanCase>();
                loanCase.LoanCaseID = Guid.NewGuid();
                loanCase.LoanID = loanID;
                loanCase.CaseNumber = caseNumber;
                loanCase.Notes = notes;
                loanCase.CaseDate = caseDate;
                _LoanRepository.CreateLoanCase(loanCase);
                var processInstID = _WfService.GetProcessInstanceIDByEntity(loanID);
                _WfService.Move(ActionTypes.Procecute, processInstID, RegistryInfo.UserID, notes, null);

                trans.Commit();
            }
        }
    }
}
